import os
import csv
import json
import random
import string
import requests
from django.http import JsonResponse, HttpResponse, QueryDict
from django.shortcuts import render, redirect
from django.db.models import Q
from app01 import models
from app01.forms.account import SendSmsForm, RegisterFrom, LoginFrom, LoginSMSForm, ForgotForm, ForgotResetForm, \
    ForgotPWDForm
from utils.encrypt import md5  # 引用自定义的加密md5
from django.core.validators import RegexValidator
from django.contrib.auth.mixins import LoginRequiredMixin  # 只有登录后才可使用的权限管理
from django.core.serializers import serialize, deserialize
from django.core.mail import send_mail  # 发送邮件用
from django_redis import get_redis_connection  # django的redis数据库连接
from django.views.decorators.csrf import csrf_exempt


# 通过用户请求获取其ip
def get_client_ip(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip


# 通过用户ip获取取地点
def get_user_location_by_ip(ip):
    response = requests.get(f'http://ipinfo.io/{ip}/json')
    if response.status_code == 200:
        location = response.json()
        return {
            'city': location.get('city', 'Unknown'),      # 城市
            'region': location.get('region', 'Unknown'),  # 地域:省
            'country': location.get('country', 'Unknown'),  # 国家
            'latitude': location.get('loc', 'Unknown'),   # 纬度
            'longitude': location.get('lon', 'Unknown'),  # 经度
        }
    else:
        return 'Unknown'


def index(request, aid=None):
    # 获取用户ip
    user_ip = get_client_ip(request)
    # 获取用户地点信息
    user_location = get_user_location_by_ip(user_ip)
    city = user_location.get('city')
    if city == 'Unknown' or not city:
        city = '乐山'

    # 获取今天和未来2天数据
    uri1 = ' https://api.seniverse.com/v3/weather/daily.json?key=STorjYZ-fnd9oclE2&location=%s&language=zh-Hans&unit=c&start=0&days=5' % city
    # 获取生活指数
    uri2 = 'https://api.seniverse.com/v3/life/suggestion.json?key=STorjYZ-fnd9oclE2&location=%s&language=zh-Hans' % city
    weather_future = requests.get(url=uri1).json()
    living_index = requests.get(url=uri2).json()
    # print(weather_future)
    # print(living_index)

    currentCity = weather_future.get('results')[0].get('location').get('name')  # 所在城市
    weather_now = weather_future.get('results')[0].get('daily')[0]              # 今天天气
    weather_two = weather_future.get('results')[0].get('daily')[1]              # 明天天气
    weather_three = weather_future.get('results')[0].get('daily')[2]            # 后天天气
    living_index = living_index.get('results')[0].get('suggestion')
    # 先算好比例，再传给后端, 降水量的显示刻度
    rainfall_proportion = float(weather_now.get('rainfall'))*0.75+5
    precip_proportion = float(weather_now.get('precip'))*0.75+5
    wind_speed_proportion = float(weather_now.get('wind_speed'))*0.75+5
    container = {}
    if aid is None or aid == 0:
        container = {'currentCity': currentCity,
                     'weather_now_a': weather_now,
                     'weather_now': weather_now,
                     'weather_two': weather_two,
                     'weather_three': weather_three,
                     'living_index': living_index,
                     'rainfall_proportion': rainfall_proportion,
                     'precip_proportion': precip_proportion,
                     'wind_speed_proportion': wind_speed_proportion}
    if aid == 1:
        container = {'currentCity': currentCity,
                     'weather_now_a': weather_now,
                     'weather_now': weather_two,  # 为前端解析为第二天
                     'weather_two': weather_two,
                     'weather_three': weather_three,
                     'living_index': living_index,
                     'rainfall_proportion': rainfall_proportion,
                     'precip_proportion': precip_proportion,
                     'wind_speed_proportion': wind_speed_proportion}
    if aid == 2:
        container = {'currentCity': currentCity,
                     'weather_now_a': weather_now,
                     'weather_now': weather_three,  # 为前端解析为第三天
                     'weather_two': weather_two,
                     'weather_three': weather_three,
                     'living_index': living_index,
                     'rainfall_proportion': rainfall_proportion,
                     'precip_proportion': precip_proportion,
                     'wind_speed_proportion': wind_speed_proportion}

    return render(request, 'website/src/index.html', container)


def login(request):
    if request.method == 'GET':
        form = LoginFrom(request)
        return render(request, 'login/login.html', {'form': form})
    form = LoginFrom(request, data=request.POST)
    if form.is_valid():
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        # user_object = models.UserInfo.objects.filter(username=username,password=password).first()
        # 如果邮箱和密码  或者 手机和密码 跟数据库相等
        user_object = models.AdminCustomer.objects.filter(Q(email=username) | Q(mobile=username)).filter(
            password=password).first()
        if user_object:
            # 邮箱和密码  或者 手机和密码 正确
            request.session['user_id'] = user_object.id

            request.session.set_expiry(60 * 60 * 24 * 14)  # 14天后过期
            return redirect('index')
        form.add_error('username', '用户名或密码错误')

    return render(request, 'login/login.html', {'form': form})


def login_sms(request):
    """短信登录"""
    if request.method == 'GET':
        form = LoginSMSForm()
        return render(request, 'login/login_sms.html', {'form': form})

    form = LoginSMSForm(data=request.POST)
    if form.is_valid():
        # 用户输入正确，登录成功，若要存入session，就要把forms返回的user_object拿到
        mobile = form.cleaned_data['mobile']
        user_object = models.AdminCustomer.objects.filter(mobile=mobile).first()
        request.session['user_id'] = user_object.id
        request.session.set_expiry(60 * 60 * 24 * 14)  # 14天后过期

        return JsonResponse({'status': True, 'data': '/'})
    return JsonResponse({'status': False, 'error': form.errors})


def image_code(request):
    """生成图片验证码"""
    from io import BytesIO
    from utils.image_code import check_code

    image_object, code = check_code()

    # 把图片写到内存中
    stream = BytesIO()
    image_object.save(stream, 'png')
    # 把code写入session,并设置60秒之后过期(默认14天)
    request.session['image_code'] = code
    request.session.set_expiry(60)

    return HttpResponse(stream.getvalue())


def logout(request):
    request.session.delete()
    return redirect('/login/')


def forgot(request):
    """ 忘记密码，用邮箱重置 """
    if request.method == 'GET':
        form_set = ForgotPWDForm()
        form = ForgotForm()
        return render(request, 'login/forgot.html', {'form': form, 'form_set': form_set})  # 忘记密码
    if request.method == 'POST':
        # 发送邮箱验证码进行验证
        form = ForgotForm(data=request.POST)
        if form.is_valid():
            # 生成验证码(取随机的4位阿拉伯数字) ['0', '2', '4', '1']
            captcha = ''.join(random.sample(string.digits, 4))
            # 存储到数据库中
            # CaptchaModel.objects.update_or_create(email=email, defaults={'captcha': captcha})
            email = form.cleaned_data['email']
            # 验证码 写入redis（django-redis）
            conn = get_redis_connection()
            conn.set(email, captcha, ex=120)

            send_mail('您的注册验证码', message=f'您的注册验证码是: {captcha}', recipient_list=[email], from_email=None)
            return JsonResponse({"status": True, "data": "/reset/"})  # "data": "/reset/"还用不到
    return JsonResponse({"status": False, "error": form.errors})


def forgot_reset(request):
    if request.method == 'POST':
        # 重置密码验证
        form = ForgotResetForm(data=request.POST)
        if form.is_valid():
            return JsonResponse({"status": True, "data": "/reset/"})
        return JsonResponse({"status": False, "error": form.errors})


@csrf_exempt
def forgot_resetPWD(request):
    if request.method == 'POST':
        formData1 = request.POST.get('formData1')
        formData2 = request.POST.get('formData2')
        # 对formData1和formData2进行处理，解析成QueryDict字典
        formData1_dict = QueryDict(formData1)
        formData2_dict = QueryDict(formData2)
        email = formData1_dict.get('email')
        form_set = ForgotPWDForm(formData2_dict)
        if form_set.is_valid():
            password = form_set.cleaned_data['password']
            models.AdminCustomer.objects.update_or_create(email=email, defaults={'password': password})
            return JsonResponse({"status": True, "data": "/login/"})
        return JsonResponse({"status": False, "error": form_set.errors})


def send_sms(request):
    # 用forms来校验,多传一个参数request给forms去校验
    form = SendSmsForm(request, data=request.GET)
    if form.is_valid():
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})


def register(request):
    if request.method == 'GET':
        form = RegisterFrom()
        return render(request, 'login/register.html', {'form': form})  # 注册
    # 用forms组件功能进行验证
    form = RegisterFrom(data=request.POST)  # 把用户输入的所有内容data放进去,forms就会逐一帮你校验
    if form.is_valid():
        print('注册检验通过')
        # 校验通过,保存数据
        form.save()  # 会保存有定义的字段，舍弃没有定义的字段，并返回最后保存的这条记录对象，instance=form.save()
        print('注册检验通过，数据已保存')
        return JsonResponse({'status': True, 'data': '/login/'})  # 注册成功让其跳转到登录
    print('注册检验失败！！！')
    return JsonResponse({'status': False, 'error': form.errors})  # 注册失败返回错误信息


def reward(request):
    return render(request, 'reward/reward.html')  # 打赏


def button(request):
    return render(request, 'website/src/pages/ui-features/buttons.html')  # 按钮-卧室用以后
